package com.imooc.business.core.executor.storage;

import com.imooc.business.builder.StorageSqlBuilder;
import com.imooc.business.context.DataContext;
import com.imooc.business.domain.Rule;
import com.imooc.business.domain.Storage;
import com.imooc.infra.repository.jdbc.DynamicJdbcRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Component
public class DefaultStorageProcess implements StorageProcess{

    private final DynamicJdbcRepository dynamicJdbcRepository;
    public DefaultStorageProcess(DynamicJdbcRepository dynamicJdbcRepository) {
        this.dynamicJdbcRepository = dynamicJdbcRepository;
    }
    @Override
    public void process(DataContext context) {
        DataContext.CacheModel cacheModel = context.getCacheModel();
        List<Map<String, Object>> results = cacheModel.getResults();

        Rule rule = cacheModel.getRule();
        if (CollectionUtils.isEmpty(results)) {
            log.warn("没有需要存储的数据，ruleId:{}, businessId:{}", rule.getRuleId(), rule.getBusinessId());
            return;
        }

        Storage storage = rule.getStorage();
        String dataSource = storage.getDataSource();
        String tableName = storage.getTableName(rule.getEnName(), cacheModel.getDimension(), cacheModel.getPeriod());

        Map<String, Object> params = context.buildCollectParams();

        String deleteSql = StorageSqlBuilder.buildDeleteSql(tableName, cacheModel.getDimension());
        String insertSql = StorageSqlBuilder.buildInsertSql(tableName, results);
        dynamicJdbcRepository.saveAndDelete(dataSource, deleteSql, insertSql, params, results);
    }
}
